package cn.gov.scds.util.city;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.gov.scds.entity.Content;
import cn.gov.scds.jdbc.DBConnection;
import cn.gov.scds.jdbc.DBUitl;
import cn.gov.scds.util.AppContentUtil;
import cn.gov.scds.util.DataContentUtil;
import cn.gov.scds.util.HtmlRegexpUtil;
import cn.gov.scds.util.MediaUtil;

import com.trs.web2frame.domain.WDocumentMgr;
import com.trs.web2frame.entity.WDocument;

import oracle.sql.CLOB;

public class DazhouDataMoveUtil extends DataMoveUtilBase{

	/*
	 * 达州地方税务局数据迁移工具
	 * */
	
	public static Connection connect=null;
	public static Statement statement=null;
	public static ResultSet resultSet=null;
	private static boolean appendixFlag=false;
	int y_channel;
	static int x_channel;
	static String city_name;
	CLOB clob = null;
	
	/*工具入口*/
	@Override
	public void runMove() {
		// TODO Auto-generated method stub
		//wai_moveNews();
		
		nei_moveNews();
	}
 
	/*外网部分*/
	private void wai_moveNews(){
		int[] y_channel={762};
		x_channel=3671;
		city_name="四川省达州市地方税务局";
		
		String sqlStr="select * from PE_Article where CreateTime <'2015-09-10 00:00:00' and ClassId in(";
		StringBuffer sqlBuffer=new StringBuffer();
		
		for(int i=0;i<y_channel.length;i++){
			if(i==0){
				sqlBuffer.append(y_channel[i]);
			}else{
				sqlBuffer.append(","+y_channel[i]);
			}
			
		}
		sqlStr=sqlStr+sqlBuffer.toString()+") order by ArticleID asc";
		
		//String sqlStr="select * from mynews where NEWSTYPE like '图片新闻'";
		
		System.out.println("打印SQL语句："+sqlStr);
		
		int countIndex=1;
        statement=DBUitl.getStatement(DBConnection.getConnection());
		ResultSet resultSet=DBUitl.getResultSet(statement,sqlStr);
		try {
			while (resultSet.next()) {
				Content content=new Content();
				content.setContentID(resultSet.getInt("ArticleID"));
				if(resultSet.getString("Title")==null){
					content.setTitle_1("暂无标题");
				}else{
					content.setTitle_1(resultSet.getString("Title"));
				}
				System.out.println("源文档编号："+content.getContentID());
				
				String songContent=resultSet.getString("Content");
				//处理clob字段
				/*String songContent="";
				clob = (oracle.sql.CLOB) resultSet.getClob("CONTENT_2");
				if(clob!=null){
					BufferedReader in = new BufferedReader(clob.getCharacterStream());
					StringWriter out = new StringWriter();
					int c=0;
					try {
						while ((c = in.read()) != -1) {
						     out.write(c);
						}
						songContent=out.toString();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						//e1.printStackTrace();
						System.out.println(".....+++此处文档异常...=======");
						songContent="暂无内容！";
					}
					
					
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
						System.out.println(".....+++此处文档输出流关闭异常...=======");
					}
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
					    //e.printStackTrace();
						System.out.println(".....+++此处文档输入流关闭异常...=======");
					}
				}else{
					songContent="暂无内容";
				}*/
				
				if(songContent==null){
					content.setItem_text("");
				}else{
					System.out.println("内容："+songContent);
				    String itext = null;
					//itext = ClobToString(clob);
					itext=songContent;
					String item_text=DataContentUtil.replaceContentCharacter(itext);
					//String item_text="";
					/*String picInfoString=resultSet.getString("U3");
					if(picInfoString==null){
						content.setItem_text(item_text);
					}else if(picInfoString.isEmpty()){
						content.setItem_text(item_text);
					}else{
						picInfoString="<img src=\"http://155.24.16.2"+picInfoString+"\"/>";
						content.setItem_text(picInfoString+item_text);
					}*/
					content.setItem_text(item_text);
					
				}
				content.setWrite_date(resultSet.getTimestamp("CreateTime"));
				//content.setWrite_user(resultSet.getInt("WRITE_USER"));
				content.setAudit_date(resultSet.getTimestamp("UpdateTime"));
				//content.setAudit_user(resultSet.getInt("AUDIT_USER"));
				content.setIssue_date(resultSet.getTimestamp("CreateTime"));
				//content.setIssue_user(resultSet.getInt("ISSUE_USER"));
				int showNumber=resultSet.getInt("Hits");
				content.setShow_number(showNumber==0?0:showNumber);
				String contentFrom=resultSet.getString("CopyFrom");
				content.setContent_from(contentFrom==null?city_name:contentFrom);
				//content.setDocchannel(readItemIterator(resultSet.getInt("ITEM_ID")));
				
				System.out.println("文档标题："+content.getTitle_1());
				System.out.println("WRITE_DATE："+content.getWrite_date());
				//System.out.println("WRITE_USER："+resultSet.getInt("WRITE_USER"));
				System.out.println("AUDIT_DATE："+content.getAudit_date());
				//System.out.println("AUDIT_USER："+resultSet.getInt("AUDIT_USER"));
				System.out.println("ISSUE_DATE："+content.getIssue_date());
				//System.out.println("ISSUE_USER："+resultSet.getInt("ISSUE_USER"));
				System.out.println("SHOW_NUMBER："+content.getShow_number());
				System.out.println("CONTENT_FROM："+content.getContent_from());
				
				//调用附件读取方法，一个文档读取一次数据附件。
				//connect=DBConnection.getConnection();
				//content.setContentFiles(readContentFile(connect,content.getContentID()));
				//System.out.println("附件个数："+content.getContentFiles().size());
				
				System.out.println("==============文档读取完毕,,,,,,,,,,,,");
				
				//调用WCM文档推送方法，将封装好后的文档推送到新数据库中。
				
				try {
				   testSaveAll(content);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("当前处理记录是第："+countIndex);
				countIndex++;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				resultSet.close();
				statement.close();
				//connect.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("好无聊！");
	}
	
	/*内网部分*/
	private void nei_moveNews(){
		int[] y_channel={366};
		x_channel=4684;
		city_name="四川省达州市地方税务局";
		
		String sqlStr="select * from PE_Article where ClassID in(";
		StringBuffer sqlBuffer=new StringBuffer();
		
		for(int i=0;i<y_channel.length;i++){
			if(i==0){
				sqlBuffer.append(y_channel[i]);
			}else{
				sqlBuffer.append(","+y_channel[i]);
			}
			
		}
		sqlStr=sqlStr+sqlBuffer.toString()+") order by ArticleID asc";
		//String sqlStr="select * from PE_Article";
		//String sqlStr="select * from mynews where NEWSTYPE like '图片新闻'";
		System.out.println("打印SQL语句："+sqlStr);
		int countIndex=1;
        statement=DBUitl.getStatement(DBConnection.getConnection());
		ResultSet resultSet=DBUitl.getResultSet(statement,sqlStr);
		try {
			while (resultSet.next()) {
				Content content=new Content();
				content.setContentID(resultSet.getInt("ArticleID"));
				String contentTitle=resultSet.getString("Title");
				if(contentTitle==null){
					content.setTitle_1("暂无标题");
				}else{
					content.setTitle_1(contentTitle);
				}
				System.out.println("源文档编号："+content.getContentID());
				
				String songContent=resultSet.getString("Content");
				if(songContent==null){
					content.setItem_text("");
				}else{
					//System.out.println("内容："+songContent);
				    String itext = null;
					//itext = ClobToString(clob);
					itext=songContent;
					String item_text=DataContentUtil.replaceContentCharacter(itext);
					//String item_text="";
					/*String picInfoString=resultSet.getString("U3");
					if(picInfoString==null){
						content.setItem_text(item_text);
					}else if(picInfoString.isEmpty()){
						content.setItem_text(item_text);
					}else{
						picInfoString="<img src=\"http://155.24.16.2"+picInfoString+"\"/>";
						content.setItem_text(picInfoString+item_text);
					}*/
					content.setItem_text(item_text);
					
				}
				content.setWrite_date(resultSet.getTimestamp("CreateTime"));
				//content.setWrite_user(resultSet.getInt("WRITE_USER"));
				content.setAudit_date(resultSet.getTimestamp("UpdateTime"));
				//content.setAudit_user(resultSet.getInt("AUDIT_USER"));
				//content.setIssue_date(resultSet.getTimestamp("CreateTime"));
				//content.setIssue_user(resultSet.getInt("ISSUE_USER"));
				int showNumber=resultSet.getInt("Hits");
				content.setShow_number(showNumber==0?0:showNumber);
				String contentFrom=resultSet.getString("CopyFrom");
				content.setContent_from(contentFrom==null?city_name:contentFrom);
				//content.setDocchannel(readItemIterator(resultSet.getInt("ITEM_ID")));
				
				System.out.println("文档标题："+content.getTitle_1());
				System.out.println("WRITE_DATE："+content.getWrite_date());
				//System.out.println("WRITE_USER："+resultSet.getInt("WRITE_USER"));
				System.out.println("AUDIT_DATE："+content.getAudit_date());
				//System.out.println("AUDIT_USER："+resultSet.getInt("AUDIT_USER"));
				System.out.println("ISSUE_DATE："+content.getIssue_date());
				//System.out.println("ISSUE_USER："+resultSet.getInt("ISSUE_USER"));
				System.out.println("SHOW_NUMBER："+content.getShow_number());
				System.out.println("CONTENT_FROM："+content.getContent_from());
				
				System.out.println("==============文档读取完毕,,,,,,,,,,,,");
				
				//调用WCM文档推送方法，将封装好后的文档推送到新数据库中。
				
				try {
				   testSaveAll(content);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("当前处理记录是第："+countIndex);
				countIndex++;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				resultSet.close();
				statement.close();
				//connect.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("好无聊！");
	}
	
	/*
	 * 根据旧数据库读取的文档，写入到新的数据库。
	 * */
	/**
	 * 保存文档及其所有相关项，包括引用栏目，附件，相关文档
	 * 
	 * @param _oDocument
	 * @throws Exception 
	 */
	private static void saveAll(WDocument _oDocument) throws Exception {
		long recordId=WDocumentMgr.save(_oDocument);
		WDocumentMgr.quoteTo(_oDocument);
		
		if(appendixFlag==true){
			try {
				WDocumentMgr.saveAppendixs(_oDocument);
				//WDocumentMgr.saveRelations(_oDocument);
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("妈的，附件后缀格式又不支持了！");
			}
			
		}
		//WDocumentMgr.saveAppendixs(_oDocument);
		//WDocumentMgr.saveRelations(_oDocument);
		
		
	}
	
	/** 附件类型标识：文档附件 */
    public final static int FLAG_DOCAPD = 10; // 文件:Document Appendix

    /** 附件类型标识：文档图片 */
    public final static int FLAG_DOCPIC = 20; // 图片:Document Picture

    /** 附件类型标识：HTML */
    public final static int FLAG_HTMLPIC = 30; // HTML图片:Html Picture

    /** 附件类型标识：链接附件 */
    public final static int FLAG_LINK = 40; // 链接:Link
    
    
	public static void testSaveAll(Content content) throws Exception {
		   System.out.println("=========进入文档写方法======");
		  WDocument oDocument = new WDocument();
		
		  oDocument.setFieldValue("ChannelId", x_channel);
		  oDocument.setFieldValue("ObjectId", new Integer(0));
		
		  oDocument.setFieldValue("DocTitle", content.getTitle_1());
		  oDocument.setFieldValue("DOCTYPE", new Integer(20));
		  System.out.println("content.getWrite_date()"+content.getWrite_date());
		  oDocument.setFieldValue("CRTIME", content.getWrite_date());
		  oDocument.setFieldValue("DOCRELTIME", content.getWrite_date());
		  String htmlContent=new HtmlRegexpUtil().fiterHtmlTag(content.getItem_text(), "a");
		  htmlContent=htmlContent.replace("</a>", "");
		  htmlContent=new HtmlRegexpUtil().fiterHtmlTag(htmlContent, "A");
		  htmlContent=htmlContent.replace("</A>", "");
		  //System.out.println("处理后的内容："+htmlContent);
		  oDocument.setFieldValue("DOCCONTENT", AppContentUtil.replaceSpecialCharacter(htmlContent));
		  System.out.println("打印内容长度："+content.getItem_text().length());
		  oDocument.setFieldValue("DocHtmlCon", DataContentUtil.baseStyle+htmlContent);
		  oDocument.setFieldValue("DOCSOURCENAME ", content.getContent_from()==null?city_name:content.getContent_from());
		  oDocument.setFieldValue("HITSCOUNT ", content.getShow_number());
		  
		  
		  //System.out.println("创建时间："+content.getWrite_date());
		  //System.out.println("发布时间："+content.getIssue_date());
		  //System.out.println("撰写时间："+content.getWrite_date());
		  
		
		  /*if(content.getContentFiles().size()!=0||content.getContentFiles()!=null){
			  for(int i=0;i<content.getContentFiles().size();i++){
				  Map<String,Object> oAppendixMore=new HashMap<String, Object>();
				  oAppendixMore.put("APPDESC", content.getContentFiles().get(i).getFile_info());
				  String localFile="G://AppData/SCDS/Appendix/"+content.getContentFiles().get(i).getFile_name();
				  //oDocument.addAppendix(FLAG_DOCAPD, localFile);
				  oDocument.addAppendix(FLAG_DOCAPD, localFile, oAppendixMore);
				  //oDocument.addRelation(898);
				  //oDocument.addRelation(884);
			  }
			oDocument.uploadAllAppendixs();
			appendixFlag=true;
		  }*/
		  
		  /*抓取文件中的超链接，上传到附件*/
		  List<String> linkAppendix=new HtmlRegexpUtil().replaceHtmlTag3(content.getItem_text(), "a", "href", "", "");
		  if(linkAppendix.size()!=0){
			  for(int i=0;i<linkAppendix.size();i++){
				  Map<String,Object> oAppendixMore=new HashMap<String, Object>();
				  String tempFile=linkAppendix.get(i).replace("http://155.76.16.9/", "");
				  String localFile="G://AppData/SCDS/Appendix/"+tempFile;
				  oDocument.addAppendix(FLAG_DOCAPD, localFile, oAppendixMore);
			  }
		  }
		  
		  oDocument.uploadAllAppendixs();
		  appendixFlag=true;
		
		  saveAll(oDocument);
	}
	
	/*
	 * 图片路径替换
	 * */
	private String ImagePathReplace(String src){
		src=src.replace("src=\"/UserFiles", "src=\"http://www.scdz-l-tax.gov.cn/UserFiles");
		//src=src.replace("src=\"/", "src=\"http://155.16.16.60:7001/");
		//src=src.replace("src=\"/", "src=\"http://155.16.161.140/");
		
		
		/*自贡地税内网图片路径替换*/
		src=src.replace("src=\"/", "src=\"http://www.scdz-l-tax.gov.cn/");
		
		return src;
	}
	
	/*
	 * 时间戳转换为日期
	 * */
	private Timestamp getDate(int dateNumber){
		Date nDate=null;
		Timestamp dateTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String date = sdf.format(new Date(dateNumber*1000));
		
		try {
			//nDate=(Date) sdf.parse(date);
			dateTime = Timestamp.valueOf(date);
			//nDate=(Date)dateTime;
		}finally{
			return dateTime;
		}
	}
}
